package com.atguigu.connection;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionTest {
    @Test
    public void testConnection1 () {
        try {
            Driver driver = new com.mysql.jdbc.Driver();

            String url = "jdbc:mysql://localhost:3306/test";

            Properties info = new Properties();
            info.setProperty("user", "root");
            info.setProperty("password", "960405");

            Connection conn = driver.connect(url, info);
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public  void testConnection2 () {
        try {
            // 使用反射实现类对象
            Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();

            String url = "jdbc:mysql://localhost:3306/test";

            Properties info = new Properties();
            info.setProperty("user", "root");
            info.setProperty("password", "960405");

            Connection conn = driver.connect(url, info);
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testConnection3 () throws Exception {
        Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();

        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "960405";
        // 注册驱动
        DriverManager.registerDriver(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

    @Test
    public void testConnection4 () throws Exception {
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "960405";

        // 加载Driver，自动执行registerDriver
        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

    @Test
    public void testConnection5 () throws Exception {
        InputStream inputStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(inputStream);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        Class.forName(driverClass);

        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }
}
